package my.sample.netflow.generator;

import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import com.mongodb.MongoClient;

public class NetflowGenMain {

	public static void main(String[] args) {
		
		if ( args.length < 8 ) {
			printHelp();
			System.exit(0);
		}

		ExecutorService routerExeService = Executors.newFixedThreadPool(Integer.parseInt(args[2]));
		
		// 0 - mongodb ip
		// 1 - mongodb port
		// 2 - application thread count
		// 3 - start range
		// 4 - total insert count
		// 5 - insert count per thread
		// 6 - database
		// 7 - collection
		
		MongoClient client = null;
		try {
			client = new MongoClient(args[0], Integer.parseInt(args[1]));
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		
		Date startTime = new Date();
		int countPerThread = Integer.parseInt(args[5]);
		int startRange = Integer.parseInt(args[3]);
		int endRange = startRange + Integer.parseInt(args[4]);

		List<Future<Integer>> futureList = new ArrayList<Future<Integer>>();
		for (int i = startRange; i < endRange; i += countPerThread) {
			NetflowGen threadObj = new NetflowGen(i, countPerThread, client, args[6], args[7]);
			futureList.add(routerExeService.submit(threadObj));
		}

		try {
			for (Future<Integer> future : futureList) {
				future.get();
			}
		} catch (Exception e) {
			System.out.println("Aggregator : " + e);
		}

		Date endTime = new Date();
		
		System.out.println("jobs successfully completed : " + futureList.size());
		futureList.clear();
		System.out.println("executor service shutting down....");
		routerExeService.shutdown();
		System.out.println("total time taken : " + (endTime.getTime() - startTime.getTime()));
		
	}
	
	private static void printHelp() {
		System.out.println("Command parameters - 8");
		System.out.println("\t" + "mongodb ip");
		System.out.println("\t" + "mongodb port");
		System.out.println("\t" + "application thread count");
		System.out.println("\t" + "start range");
		System.out.println("\t" + "total insert");
		System.out.println("\t" + "insert count per thread");
		System.out.println("\t" + "database");
		System.out.println("\t" + "collection");
		System.out.println("example : ");
		System.out.println("localhost 27017 10 1 1000 100 netflowdb netflow_collection");
	}

}
